﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ServiceApplication.Service.Basic;
using CommonLibrary.DataModel.Basic;
using OAclient.Models;
using System.IO;
using CommonLibrary.Common;
using MethodWorx.AspNetComet.Core;
using OAclient.Common;
using System.Data;
using System.Net.Mail;
using OAclient.Filters;
using System.Text;
using ValueMail;
using ValueMail.Send.Infrastructure;
using ValueMail.Receive.IMAP.Infrastructure;
//using Server.Channels;

namespace OAclient.Controllers
{
    [VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    public class MessageController : Controller
    {
        //
        // GET: /Message/
        BasicService bs = new BasicService();
        private const Int32 PageSize = 15;
        Encoding utf8 = Encoding.UTF8;

        private ClientManager manager = new ClientManager();

        String baseUrl = Path.Combine(ComVariable.StoreUrl, "webstore");

        //发送站内信 msg-1
        public ActionResult MsgSend(UserModel user, int? receiver_id, String msg_id, String operType)
        {
            ViewData["creater_id"] = user.user.user_id;
            if (receiver_id.HasValue)
            {
                ViewData["receiver_ids"] = receiver_id.ToString();
                UserEntity userEntity = bs.QueryUser(receiver_id.Value);
                ViewData["receiver_names"] = userEntity.user_name;
            }
            ViewData["operType"] = operType;
            ViewData["msg_id"] = msg_id;


            ViewData["appendix"] = ZTreeHelper.Serialize(bs.GetStoreTree(user.user.user_id.ToString()));
            return PartialView();
        }

        public ActionResult MsgSendTest()
        {
            return PartialView();
        }

        //msg-2
        public ActionResult MsgSendList(UserModel user, Int32? page)
        {
            var currPage = page ?? 1;
            //var dt = bs.QueryMsgsByCreaterId(user.user.user_id);
            var title = Request.Form["searchtitle_msgsend"] ?? Request.QueryString["title"];
            var content = Request.Form["searchcontent_msgsend"] ?? Request.QueryString["content"];
            var stime = Request.Form["searchstime_msgsend"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_msgsend"] ?? Request.QueryString["etime"];

            ViewData["searchtitle_msgsend"] = title;
            ViewData["searchcontent_msgsend"] = content;
            ViewData["searchstime_msgsend"] = stime;
            ViewData["searchetime_msgsend"] = etime;

            var dt = bs.QueryMsgByCodition(user.user.user_id, title, content, stime, etime, 0, null);
            var temp_drs = dt.Select("标题 not like '企业公告%'");
            if (temp_drs.Length > 0)
                dt = temp_drs.CopyToDataTable();
            else
                dt = dt.Clone();
            var pageInfo = new PagingInfo
            {
                CurrentPage = currPage,
                ItemsPerPage = PageSize,
                TotalItems = dt.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((currPage - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = dt;
            return PartialView();
        }

        //msg-3
        public ActionResult MsgDrftList(UserModel user, Int32 page)
        {

            var title = Request.Form["searchtitle_msgdrftlist"] ?? Request.QueryString["title"];
            var content = Request.Form["searchcontent_msgdrftlist"] ?? Request.QueryString["content"];
            var stime = Request.Form["searchstime_msgdrftlist"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_msgdrftlist"] ?? Request.QueryString["etime"];

            ViewData["searchtitle_msgdrftlist"] = title;
            ViewData["searchcontent_msgdrftlist"] = content;
            ViewData["searchstime_msgdrftlist"] = stime;
            ViewData["searchetime_msgdrftlist"] = etime;

            var dt = bs.QueryMsgByCodition(user.user.user_id, title, content, stime, etime, 1, null);
            var pageInfo = new PagingInfo
            {
                CurrentPage = page,
                ItemsPerPage = PageSize,
                TotalItems = dt.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((page - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = dt;
            return PartialView();
        }

        //msg-4
        public ActionResult MsgReceiveList(UserModel user, Int32? page)
        {
            var title = Request.Form["searchtitle_msgreceive"] ?? Request.QueryString["title"];
            var content = Request.Form["searchcontent_msgreceive"] ?? Request.QueryString["content"];
            var stime = Request.Form["searchstime_msgreceive"] ?? Request.QueryString["stime"];
            var etime = Request.Form["searchetime_msgreceive"] ?? Request.QueryString["etime"];

            ViewData["searchtitle_msgreceive"] = title;
            ViewData["searchcontent_msgreceive"] = content;
            ViewData["searchstime_msgreceive"] = stime;
            ViewData["searchetime_msgreceive"] = etime;

            var dt = bs.QueryReceveMsgByCondition(user.user.user_id, title, content, stime, etime, 0, null);
            var temp_drs = dt.Select("标题 not like '企业公告%'");
            if (temp_drs.Length > 0)
                dt = temp_drs.CopyToDataTable();
            else
                dt = dt.Clone();

            var currPage = page ?? 1;
            var pageInfo = new PagingInfo
            {
                CurrentPage = currPage,
                ItemsPerPage = PageSize,
                TotalItems = dt.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;
            if (dt.Rows.Count > 0)
                dt = dt.AsEnumerable().Skip((currPage - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = dt;
            return PartialView();
        }

        //msg-4-1
        public ActionResult MsgShow(int msg_id, UserModel user)
        {

            MsgEntity msgEntity = bs.QueryMsg(msg_id);
            ViewData["msg_id"] = msgEntity.msg_id;
            ViewData["title"] = msgEntity.msg_titile;
            ViewData["content"] = Server.HtmlDecode(msgEntity.msg_content);
            ViewData["sendtime"] = msgEntity.msg_sendtime;
            UserEntity userEntity = bs.QueryUser(msgEntity.creater_id);
            ViewData["creater_id"] = userEntity.user_id;
            ViewData["creater_name"] = userEntity.user_name;
            var rootPath = produRootPath();
            var paths = CommonMethod.splitString(msgEntity.msg_appendix, ';');
            var names = CommonMethod.splitString(msgEntity.msg_appendix_name, ' ');
            var files = String.Empty;

            for (int index = 0; index < paths.Length; index++)
            {
                var fileName = paths[index].Substring(paths[index].LastIndexOf("/") + 1);
                var tmppath = HttpUtility.UrlEncode(paths[index]).ToLower();
                var tmpfilename = HttpUtility.UrlEncode(fileName).ToLower();
                files += "<a href='/Message/fileFromDisk?path=" + tmppath + "&fileName=" + tmpfilename + "'>" + names[index] + "</a><br />";
            }

            foreach (var path in paths)
            {

            }
            ViewData["msg_appendix"] = files;
            //如果不是查看自己的信，即查看收到的信，则将该msg状态改为已读
            //已读标志
            bs.DoMsgRead(msg_id, user.user.user_id);
            return PartialView();
        }

        //msg-2-1
        public ActionResult MsgShowSelf(int msg_id)
        {
            MsgEntity msgEntity = bs.QueryMsg(msg_id);
            DataTable dt_msgmx = bs.QueryMsgmx(msg_id);

            ViewData["title"] = msgEntity.msg_titile;
            ViewData["content"] = Server.HtmlDecode(msgEntity.msg_content);
            ViewData["sendtime"] = msgEntity.msg_sendtime;
            UserEntity userEntity = bs.QueryUser(msgEntity.creater_id);
            ViewData["creater_id"] = userEntity.user_id;
            ViewData["creater_name"] = userEntity.user_name;
            var rootPath = produRootPath();
            var paths = CommonMethod.splitString(msgEntity.msg_appendix, ';');
            var files = String.Empty;
            foreach (var path in paths)
            {
                var fileName = path.Substring(path.LastIndexOf("/") + 1);
                var tmppath = HttpUtility.UrlEncode(path).ToLower();
                var tmpfilename = HttpUtility.UrlEncode(fileName).ToLower();
                files += "<a href='/Message/fileFromDisk?path=" + tmppath + "&fileName=" + tmpfilename + "'>" + fileName + "</a><br />";
            }
            ViewData["dt_msgmx"] = dt_msgmx;
            ViewData["msg_appendix"] = files;
            return PartialView();
        }

        public ActionResult MsgLittle(int msg_id)
        {
            //var dt = bs.QueryMsgs(user.user.id, 0);
            //if (dt.Rows.Count == 0)
            //    return string;

            MsgEntity me = bs.QueryMsg(msg_id);

            ViewData["msg_id"] = msg_id;
            ViewData["msg_content"] = me.msg_content;
            return PartialView();
        }

        /// <summary>
        /// 这个partial用于模板的 message 显示未读消息加发送的界面
        /// </summary>
        /// <param name="user"></param>
        /// <param name="receiver_id"></param>
        /// <returns></returns>
        public ActionResult MsgPartial(UserModel user)
        {
            var dt = bs.QueryMsgs(user.user.user_id, 0);
            //将要显示的消息更新为已读
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                var msg_id = dt.Rows[i]["编码"].ToString();
                bs.DoMsgRead(int.Parse(msg_id), user.user.user_id);
            }
            ViewData["creater_id"] = user.user.user_id;
            ViewData["dt"] = dt;
            ViewData["msg_numb"] = dt.Rows.Count;
            ViewData["appendix"] = ZTreeHelper.Serialize(getAppendixNodeList(user));
            return PartialView();
        }

        public ActionResult Audio()
        {
            return View();
        }

        public ActionResult NetChat(UserModel userModel)
        {
            ViewData["user"] = userModel.user.user_loginid;
            return View();
        }

        // 获得米聊音频
        public ActionResult GetAudio(UserModel user, Int32 page)
        {
            const Int32 pageCount = 10;
            var userName = user.user.user_name;
            var path = getAudioPath(userName);
            var dirInfo = new DirectoryInfo(path);
            var files = dirInfo.GetFiles();

            var count = files.Length / pageCount;

            var jsonData = new
            {
                totalpage = files.Length % pageCount == 0 ? count : count + 1,
                audios = (from file in files
                          select new
                          {
                              filename = file.Name,
                              filepath = userName + "/" + file.Name,
                              createtime = file.CreationTime.ToString("yyyy-MM-dd")
                          }).Skip(page * pageCount).Take(pageCount).ToArray()
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public FileResult fileFromDisk(String path, String fileName)
        {
            //var rootPath = produRootPath();
            //path = path.Replace("/", "\\");
            //path = path.Substring(1);

            var filePath = Path.Combine(baseUrl, path);

            return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", fileName);
        }

        #region 邮件

        public ContentResult GetNewMailCount(UserModel user)
        {
            var se = bs.QueryStaff(user.user.staff_id);
            var mailAddress = se.staff_email;
            var password = se.staff_empsw;
            var userName = user.user.user_name;


            if (String.IsNullOrEmpty(mailAddress) || String.IsNullOrEmpty(password))
                return Content("M02"); // 邮箱账号或密码错误

            try
            {
                var client = manager.GetImapClient(mailAddress, password);
                if (client == null)
                    return Content("M02");

                client.SelectINBOX();
                var count = client.GetMailCount(SearchType.New);
                if (count == 0) return Content("M01"); // M01 没有新邮件
                else
                    return Content("<a onclick=\"checkMail()\">您有" + count + "条新邮件</a>");
            }
            catch (Exception e)
            {
                return Content("M02");
            }

        }

        // 发送邮件
        [ValidateInput(false)]
        public ActionResult MailSend(UserModel user, String operType)
        {
            var se = bs.QueryStaff(user.user.staff_id);
            //var email = se.staff_email;
            //ViewData["from"] = email;
            //ViewData["empsw"] = se.staff_empsw;
            if (String.IsNullOrEmpty(se.staff_email))
            {
                return JavaScript("alert('您的邮箱账户为空,请到个人中心设置')");
            }
            if (String.IsNullOrEmpty(se.staff_empsw))
            {
                return JavaScript("alert('您的邮箱密码为空,请到个人中心设置')");
            }

            ViewData["operType"] = operType;
            if (operType == "repeat")
            {
                var subject = Request.QueryString["subject"];
                var body = Request.QueryString["body"];
                var attach_id = Request.QueryString["attachId"];
                var attach_name = Request.QueryString["attachName"];
                ViewData["subject"] = subject;
                ViewData["body"] = body;
                ViewData["attach_id"] = attach_id;
                ViewData["attach_name"] = attach_name;
                ViewData["operType"] = "repaat";
            }
            ViewData["userName"] = user.user.user_name;
            ViewData["userId"] = user.user.user_id;
            ViewData["mailDomain"] = domainSelect();
            ViewData["appendix"] = ZTreeHelper.Serialize(bs.GetStoreTree(user.user.user_id.ToString()));
            return View();
        }

        private List<SelectListItem> domainSelect()
        {
            List<SelectListItem> list = new List<SelectListItem>(){
                new SelectListItem{
                    Text ="@skywalk.cn",
                    Value = "@skywalk.cn"
                }  ,
                new SelectListItem{
                    Text = "@gmail.com",
                    Value = "@gmail.com"
                },
                new SelectListItem{
                    Text ="@qq.com",
                    Value = "@qq.com"
                },
                new SelectListItem{
                    Text = "@163.com",
                    Value ="@163.com"
                }
            };

            /*
             ,
                new SelectListItem{
                    Text = "@gmail.com",
                    Value = "@gmail.com"
                },
                new SelectListItem{
                    Text ="@qq.com",
                    Value = "@qq.com"
                },
                new SelectListItem{
                    Text = "@163.com",
                    Value ="@163.com"
                }
             */
            return list;
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult MailSend(UserModel user)
        {
            var se = bs.QueryStaff(user.user.staff_id);
            var mailFrom = se.staff_email;
            var userName = Request.Form["userName"];
            var to = Request.Form["mailTo"];
            var subject = Request.Form["subject"];
            var text = Request.Form["text"];
            var password = se.staff_empsw;

            try
            {
                var client = manager.GetSmtpClient(mailFrom, password, userName);
                var sendModel = new SendModel();
                sendModel.Subject = subject;
                sendModel.Body = text;
                var mailTo = CommonMethod.splitString(to);
                for (int i = 0; i < mailTo.Length; i++)
                {
                    sendModel.AddTo(mailTo[i]);
                }

                var attachment = Request.Form["appendixHi"];
                if (!String.IsNullOrEmpty(attachment))
                {
                    var paths = CommonMethod.splitString(attachment, ';');
                    foreach (var item in paths)
                    {
                        var temp = item.Replace("/", "\\");
                        //var path = root + temp;
                        var path = Path.Combine(baseUrl, temp);
                        sendModel.AddAttachmend(path);
                    }
                }

                client.SendMail(sendModel);
                client.Dispose();

            }
            catch (InvalidOperationException ex)
            {
                return JavaScript("alert('" + ex.Message + "')");
            }
            catch (SmtpException)
            {
                return JavaScript("alert('发送邮件失败,请确保账号密码正确')");
            }
            catch
            {
                return JavaScript("alert('发生未知错误,请稍后再试')");
            }
            return RedirectToAction("MailSend");
        }

        public ActionResult MailReceive(UserModel user)
        {
            var se = bs.QueryStaff(user.user.staff_id);
            var mailAddress = se.staff_email;
            var password = se.staff_empsw;
            var userName = user.user.user_name;

            if (Request.Cookies["mailAddress"] == null)
                Response.Cookies.Add(new HttpCookie("mailAddress", mailAddress));
            else
                Response.Cookies["mailAddress"].Value = mailAddress;

            if (Request.Cookies["mailPassword"] == null)
                Response.Cookies.Add(new HttpCookie("mailPassword", password));
            else
                Response.Cookies["mailPassword"].Value = password;

            if (String.IsNullOrEmpty(mailAddress))
                return JavaScript("您的邮箱为空,请到个人中心绑定");

            try
            {
                var client = manager.GetImapClient(mailAddress, password);
                if (client == null)
                    return JavaScript("alert('用户登录失败.')");

                client.SelectINBOX();
                var list = client.GetMailHeads(SearchType.New);

                ViewData["mails"] = list;

                client.Disconnect();
                client.Dispose();
            }
            catch (SmtpException)
            {
                return JavaScript("alert('发送邮件失败,请确保账号密码正确')");
            }
            catch (Exception e)
            {
                return JavaScript("alert('" + e.Message + "')");
            }
            return View();
        }

        public ActionResult MailDetail(UserModel user, String UID)
        {

            String address = String.Empty;
            String password = String.Empty;

            if (Request.Cookies["mailAddress"] != null)
                address = Request.Cookies["mailAddress"].Value;

            if (Request.Cookies["mailPassword"] != null)
                password = Request.Cookies["mailPassword"].Value;

            try
            {
                //var mail = MailHelper.GetMail(mailModel, mailIndex);
                var client = manager.GetImapClient(address, password);
                if (client == null)
                    return JavaScript("alert('用户登录失败.')");

                client.SelectINBOX();
                var mail = client.GetMailByUID(UID);
                client.StoreAddFlag(UID, StoreFlags.Seen);

                //for (int index = 0; index < mail.Attachments.Count; index++)
                //{
                //    Session[UID.ToString() + index.ToString()] = mail.Attachments[index].Data;
                //}
                ViewData["mail"] = mail;
                client.Disconnect();
                client.Dispose();
            }
            catch (SmtpException)
            {
                return JavaScript("alert('发送邮件失败,请确保账号密码正确')");
            }
            catch (Exception e)
            {
                return Content("Failed");
            }
            return View();
        }

        /// <summary>
        ///  获得邮箱树
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMailTree()
        {
            var mail_tree = ZTreeHelper.Serialize(bs.GetMailNodes());
            return Content(mail_tree);
        }

        public ActionResult GetMailTxlTree(string user_id, string type)
        {
            DataTable dt_txlgroup = bs.QueryTxlGroupByUserId(int.Parse(user_id));
            DataTable dt_txl = bs.QueryTxlForFuzzy(int.Parse(user_id), "");
            var data = from q in dt_txlgroup.AsEnumerable()
                       select new
                       {
                           id = q["小组编号"].ToString(),
                           name = q["名称"].ToString(),
                           nocheck = true,
                           @checked = false,
                           children = from p in dt_txl.AsEnumerable()
                                      where p["小组编号"].ToString() == q["小组编号"].ToString()
                                      select new
                                      {
                                          id = p["邮箱"].ToString(),
                                          name = p["名称"].ToString(),
                                          nocheck = false,
                                          @checked = false,
                                      }
                       };

            var tree = new { id = "-1", name = type, nocheck = false, @checked = false, children = data };
            return Json(tree, JsonRequestBehavior.AllowGet);
        }

        public ActionResult SaveEmail(UserModel user, String title, String context, String address, String receives, String emailId, String appname, String appid)
        {
            EmailEntity emailEnty = new EmailEntity
            {
                User_Id = user.user.user_id.ToString(),
                Email_Title = title,
                Email_Address = address,
                Email_Context = context,
                Email_Receives = receives,
                Appendix_Name = appname,
                Appendix_Id = appid
            };
            if (emailId == "")
                bs.AddEmail(emailEnty);
            else
            {

                emailEnty.Email_Id = emailId;
                bs.UpdateEmail(emailEnty);
            }
            return Content("Success");
        }

        public void SendEmail(String emailId)
        {
            bs.SendedEmail(emailId);
        }

        public ActionResult GetEmail(String emailId)
        {
            var email = bs.QueryEmail(emailId);
            var jsonData = new
            {
                id = email.Email_Id,
                title = email.Email_Title,
                context = email.Email_Context,
                address = email.Email_Address,
                receives = email.Email_Receives,
                appname = email.Appendix_Name,
                appid = email.Appendix_Id
            };

            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetEmails(UserModel user)
        {
            var email_tree = String.Empty;

            var node = getEmails(user.user.user_id.ToString());
            if (node.Nodes.Count > 0)
                email_tree = ZTreeHelper.Serialize(node);

            return Content(email_tree);
        }

        public ActionResult GetSavedMsgs(UserModel user)
        {
            var msg_tree = String.Empty;
            var node = getSavedMsg(user.user.user_id.ToString());
            if (node.Nodes.Count > 0)
                msg_tree = ZTreeHelper.Serialize(node);

            return Content(msg_tree);

        }

        public ActionResult GetSavedMsg(String msgId)
        {
            var msg = bs.QueryMsg(Int32.Parse(msgId));
            var jsonData = new
            {
                msg_id = msg.msg_id,
                receiver_ids = msg.receiver_ids,
                receiver_names = getReceiverName(msg.receiver_ids),
                title = msg.msg_titile,
                content = Server.HtmlDecode(msg.msg_content),
                appendix = msg.msg_appendix,
                appendix_name = getAppendixNames(msg.msg_appendix)
            };
            return Json(jsonData, JsonRequestBehavior.AllowGet);
        }

        public ActionResult GetMailAttachment(String index, String fileName, String uid)
        {
            string mime = FileHelper.GetFileMIME(Path.GetExtension(fileName));
            String address = String.Empty;
            String password = String.Empty;

            if (Request.Cookies["mailAddress"] != null)
                address = Request.Cookies["mailAddress"].Value;

            if (Request.Cookies["mailPassword"] != null)
                password = Request.Cookies["mailPassword"].Value;
            var client = manager.GetImapClient(address, password);
            client.SelectINBOX();
            var mail = client.GetMailByUID(uid);

            Byte[] data = mail.Attachments[Int32.Parse(index)].Data;

            return File(data, mime, fileName);
        }

        #endregion

        #region 方法

        //发送操作
        public ActionResult DoSendMsg(string title, string content, string content2, int creater_id, string receiver_ids, String appendix, String msgId, String appendixNamemsg)
        {
            var ue = bs.QueryUser(creater_id);
            if (ue == null) return Json(new ResTag(false, "用户编码无效"), JsonRequestBehavior.AllowGet);

            MsgEntity msgEntity = new MsgEntity()
            {
                msg_titile = title,
                msg_content = content,
                msg_content2 = content2,
                msg_isread = "未读",
                creater_id = creater_id,
                receiver_ids = receiver_ids,
                msg_lev = 1,
                msg_sendtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                msg_appendix = appendix,
                msg_appendix_name = appendixNamemsg
            };
            if (msgId == "")
                bs.AddMsg(msgEntity);
            else
            {
                msgEntity.msg_id = Int32.Parse(msgId);
                bs.UpdateMsg(msgEntity);
            }
            return Json(new ResTag(true, ""), JsonRequestBehavior.AllowGet);
        }

        public ActionResult SaveMsg(string title, string content, string content2, int creater_id, string receiver_ids, String appendix, String msgId, String appName)
        {
            MsgEntity msgEntity = new MsgEntity()
            {
                msg_titile = title,
                msg_content = content,
                msg_content2 = content2,
                msg_isread = "未读",
                creater_id = creater_id,
                receiver_ids = receiver_ids,
                msg_lev = 1,
                msg_sendtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                msg_appendix = appendix,
                msg_save = 1,
                msg_appendix_name = appName
            };
            if (msgId == "")
                bs.AddMsg(msgEntity);
            else
            {
                msgEntity.msg_id = Int32.Parse(msgId);
                bs.UpdateMsg(msgEntity);
            }
            ResTag resTag = new ResTag(true, "");
            return Json(resTag, JsonRequestBehavior.AllowGet);
        }


        private String getAudioPath(String userName)
        {
            var path = Server.MapPath("/");
            path = Path.Combine(path, "WebStore");
            path = Path.Combine(path, "Audio");
            path = Path.Combine(path, userName);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            return path;
        }

        private Node getAppendixNodeList(UserModel user)
        {
            var userId = user.user.user_id.ToString();
            var path = produRootPath();
            path = Path.Combine(path, userId);
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            var node = new Node();
            var Nodes = getAppendixNode(node, path, user.user.user_id.ToString());
            if (Nodes.Nodes.Count == 0)
            {
                Nodes.Text = "无附件可供添加";
                Nodes.Value = "appendix";
            }
            else
            {
                Nodes.Text = "我的附件";
                Nodes.Value = "appendix";
            }
            return Nodes;
        }

        private Node getSavedMsg(String userId)
        {
            var Node = new Node
            {
                Text = "站内信列表",
                Value = "List"
            };
            var dt = bs.QuerySavedMsg(userId);
            if (dt != null && dt.Rows.Count > 0)
            {
                var rowCount = dt.Rows.Count;
                for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
                {
                    Node.Nodes.Add(new Node
                    {
                        Text = dt.Rows[rowIndex]["标题"].ToString(),
                        Value = dt.Rows[rowIndex]["编号"].ToString()
                    });
                }
            }

            return Node;
        }

        private Node getEmails(String userId)
        {
            var Node = new Node
            {
                Text = "邮件列表",
                Value = "List"
            };
            var dt = bs.QueryEmails(userId);
            if (dt != null && dt.Rows.Count > 0)
            {
                var rowCount = dt.Rows.Count;
                for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
                {
                    Node.Nodes.Add(new Node
                    {
                        Text = dt.Rows[rowIndex]["标题"].ToString(),
                        Value = dt.Rows[rowIndex]["编号"].ToString()
                    });
                }
            }
            return Node;
        }

        private String produRootPath()
        {
            var rootPath = Server.MapPath("/");
            rootPath = Path.Combine(rootPath, "WebStore");
            rootPath = Path.Combine(rootPath, "Person");
            return rootPath;
        }

        private Node getAppendixNode(Node rootNode, String path, String userId)
        {
            var list_userfile = bs.FilesQuery(userId);
            var rootPath = produRootPath();
            var dire = new DirectoryInfo(path);
            var files = dire.GetFiles();
            foreach (var file in files)
            {
                var filePath = file.FullName.Replace(rootPath, "");
                filePath = filePath.Replace("\\", "/");
                string filename = string.Empty;
                if (list_userfile.Count > 0 && list_userfile.Where(x => file.Name.Contains(x.file_replacename)).ToArray().Count() > 0)
                    filename = list_userfile.Where(x => file.Name.Contains(x.file_replacename)).ToArray()[0].file_name;
                rootNode.Nodes.Add(new Node
                {
                    Text = filename == "" ? file.Name : filename,
                    Value = filePath
                });
            }
            var dires = dire.GetDirectories();
            foreach (var dir in dires)
                getAppendixNode(rootNode, dir.FullName, userId);
            return rootNode;
        }

        private String getReceiverName(String receiver_ids)
        {
            var names = String.Empty;
            if (receiver_ids != null && receiver_ids != "")
            {
                var ids = receiver_ids.Split(',');
                var count = ids.Length - 1;
                for (int index = 0; index < count; index++)
                {
                    names += bs.QueryUser(Int32.Parse(ids[index])).user_name;
                }
            }
            return names;
        }

        private String getAppendixNames(String appendixs)
        {
            var names = String.Empty;
            if (appendixs != null && appendixs != "")
            {
                var appendix = appendixs.Split(';');
                var count = appendix.Length - 1;
                for (int index = 0; index < count; index++)
                {
                    names += appendix[index].Substring(appendix[index].LastIndexOf('/') + 1) + " ";
                }
            }
            return names;
        }

        #endregion
    }
}
